#include<bits/stdc++.h>
using namespace std;
const int N=1e7+10,mod=998244353;
int T,n,tx,A,B,C,m,ans,L[N],R[N],num[N];
int main()
{
    freopen("guess.in","r",stdin);
    freopen("guess.out","w",stdout);
    scanf("%d",&T);
    while(T--)
    {
        ans=0;
        scanf("%d%d%d%d%d%d",&n,&tx,&A,&B,&C,&m);
        for(int i=1;i<=n;i++)
            tx=(1ll*A*tx%m*tx+1ll*B*tx+C)%m+1,++num[tx];
        for(int i=1;i<=n;i++)
            if(num[i-1]) L[i]=i-1;
            else L[i]=L[i-1];
        for(int i=n;i;i--)
            if(num[i+1]) R[i]=i+1;
            else R[i]=R[i+1];
        ;
        for(int i=1;i<=n;i++) L[i]=R[i]=num[i]=0;
    }
    return 0;
}